//
//  GQJKVOController.m
//  TotalDemo
//
//  Created by gujian on 16/7/27.
//  Copyright © 2016年 gujian. All rights reserved.
//

#import "GQJKVOController.h"
#import "TestRumtime.h"
#import <objc/runtime.h>

@implementation GQJKVOController

- (void)viewDidLoad
{
    [super viewDidLoad];

    
    [self changePrivateValueWithKVO];
    [self changePrivateValueWithRuntime];
    [self logTheVariable];
    
    [self willChangeValueForKey:@""];
}

//使用kvo改变私有变量值
- (void)changePrivateValueWithKVO
{
    TestRumtime *testRunTime = [[TestRumtime alloc] init];
    [testRunTime logThePrivateVariable];
    
    [testRunTime setValue:@"已通过KVC发生改变" forKey:@"runStr"];
    [testRunTime logThePrivateVariable];
}

//使用runtime改变私有变量值
- (void)changePrivateValueWithRuntime
{
    TestRumtime *testRuntime = [[TestRumtime alloc] init];
    [testRuntime logThePrivateVariable];
    NSString *newValue = @"已通过Runtime发生改变";
    
    NSString *privateName = @"runStr";
    const char *privateChar = [privateName UTF8String];
    Class targetClass = [TestRumtime class];
    unsigned int ivarCount = 0;
    Ivar *ivarList = class_copyIvarList(targetClass, &ivarCount);
    for (int i = 0; i < ivarCount; i++) {
        Ivar temp = ivarList[i];
        const char *name = ivar_getName(temp);
        if (strcmp(name, privateChar) == 0) {
            object_setIvar(testRuntime, temp, newValue);
            break;
        }
    }
    
    [testRuntime logThePrivateVariable];
    free(ivarList);
}

- (void)logTheVariable
{
   __unused TestRumtime *testRuntime = [[TestRumtime alloc] init];
    Class targetClass = [TestRumtime class];
    unsigned int outCount = 0;
    Ivar *ivarList = class_copyIvarList(targetClass, &outCount);
    for (int i = 0; i < outCount; i++) {
        Ivar tempIvar = ivarList[i];
        const char *name = ivar_getName(tempIvar);
        NSLog(@"ivar name:%s",name);
    }
}

@end
